<?php

namespace app\model;

use think\facade\Db;
use think\Model;

class UserModel extends Model {

    protected $table ="user";

    protected $pk = 'uid';

    private $redisModel;

    private $cacheKey="user:";

    private $yxCacheKey="user:yx:";

    private $cacheTime=5184000;

    private $appName;



    public function __construct()
    {
        parent::__construct();

        $this->appName = config('app.app_name');

        $this->redisModel = new RedisModel();
    }


    public function getTotal($where=[]){
        return Db::name($this->table)->where($where)->count();
    }


    /*
    * 获取list
    * */
    public function getList($where=[],$page = null,$limit = null,$orderField = null,$orderType = "ASC"){

        $obj =  Db::name($this->table)->where($where);

        if(!empty($page) && !empty($limit)){
            $obj = $obj->page($page, $limit);
        }

        if(!empty($orderField) && !empty($orderType)){
            $obj = $obj->order($orderField, $orderType);
        }

        $list = $obj->select();

        if($list){
            return $list->toArray();
        }

        return  [];
    }




    /*
     * 检测手机号是否被注册
     * */
    public function checkMobileIsRegister($uid,$mobile){
        $where = [];
        $where[] = ['uid','<>',$uid];
        $where[] = ['mobile','=',$mobile];
        return Db::name('user')->field("uid")->where($where)->find();
    }


    /*
     * 根据条件查询用户
     * */
    public function getUserInfoByWhere($where){
        return Db::name('user')->where($where)->find();
    }



    /*
 * 获取用户缓存 by openid
 * */
    public function getUserCacheByOpenId($openid){

        $redisKey = $this->cacheKey.$openid;

        $uid = $this->redisModel->get($redisKey);
        if($uid){
            return $this->getUserInfoByUid($uid);
        }

        $uid = $this->getUidByOpenId($openid);

        if(!empty($uid)){
            return $this->getUserInfoByUid($uid);
        }

        return [];
    }


    public function getUserCacheByYx($yx){

        $redisKey = $this->yxCacheKey.$yx;

        $uid = $this->redisModel->get($redisKey);
        if($uid){
            return $this->getUserInfoByUid($uid);
        }

        $uid = $this->getUidByYx($yx);

        if(!empty($uid)){
            return $this->getUserInfoByUid($uid);
        }

        return [];
    }



    /*
     * 获取用户信息
     *
     * */
    public function getUserInfoByUid($uid){
        if(empty($uid)){
            return [];
        }
        //检测缓存
        $user = $this->getUserCacheByUid($uid);
        if($user){
            return json_decode($user,true);
        }
        //穿透Db缓存
        $userInfo = Db::name('user')->find($uid);
        if($userInfo){
            $this->setUserCache($userInfo);
            return $userInfo;
        }
        return [];
    }


    public function getUserBaseInfoByUid($uid){
        if(empty($uid)){
            return [];
        }
        //检测缓存
        $user = $this->getUserInfoByUid($uid);
        if(empty($user)){
            return [];
        }
        return [
            "username"=>$user["username"],
            "gender"=>$user["gender"],
            "avatar"=>$user["avatar"],
            "yx"=>$user["yx"],
        ];
    }


    /*
   * 获取用户信息
   * */
    public function getUidByOpenId($openid){
        if(empty($openid)){
            return [];
        }
        return Db::name($this->table)->where("wx_openid","=",$openid)->value("uid");
    }


    public function getUidByYx($yx){
        if(empty($yx)){
            return "";
        }
        return Db::name($this->table)->where("yx","=",$yx)->value("uid");
    }



    /*
  * 获取缓存：uid->userInfo
  * */
    public function getUserCacheByUid($uid){
        $redisKey = $this->cacheKey.$uid;
        return  $this->redisModel->get($redisKey);
    }

    /*
     * 设置缓存：uid->userInfo
     * */
    public function setUserCache($userInfo){
        $redisKey1 = $this->cacheKey.$userInfo["uid"];
        $redisKey2 = $this->cacheKey.$userInfo["wx_openid"];
        $this->redisModel->set($redisKey2,$userInfo["uid"],$this->cacheTime);
        return  $this->redisModel->set($redisKey1,json_encode($userInfo,256),$this->cacheTime);
    }




    /*
     * 删除用户缓存 用uid
     * */
    public function delUserCacheByUid($uid){
        $redisKey = $this->cacheKey.$uid;
        return  $this->redisModel->delete($redisKey);
    }


    /*
  * 修改用户信息
  * */
    public function updateUserInfo($uid,$data){
        return Db::name('user')->where("uid","=",$uid)->update($data);
    }


    /*
     * 更新用户信息
     * */
    public function updateUserInfoByWxUid($uid,$req){
        $save =[];
        $save["username"] = isset($req['nickName'])  ? $req['nickName'] : "";
        $save["avatar"] = isset($req['avatarUrl'])  ? $req['avatarUrl'] : "";
        $save["mobile"] = isset($req['mobile'])  ? $req['mobile'] : "";
        $save["gender"] = isset($req['gender'])  ? $req['gender'] : 1;
        $save["birthday"] = isset($req['birthday'])  ? $req['birthday'] : "";
        $save["is_have_update"] = 1;
        return Db::name('user')->where(["uid"=>$uid])->save(array_filter($save));
    }

    /*
   * 注册
   * */
    public function registerUser($openid,$mobile,$register_from){
        $data=[];
        if(!empty($openid)){
            $data["username"] = $this->appName ."用户_". substr($openid, -4);
            $data["wx_openid"] = $openid;
        }
        if(!empty($mobile)){
            $data["username"] = $this->appName ."用户_". substr($mobile, -4);
            $data["mobile"] = $mobile;
        }
        $data["register_from"] = $register_from;
        $data["avatar"] = "";
        $data["create_at"] = date("Y-m-d H:i:s", time());
        $data['register_from'] = "wxapp";
        return Db::name('user')->insertGetId($data);
    }


    public function incrUserFeild($uid,$feild, $num){
        $where =[];
        $where['uid'] = $uid;
        return Db::name($this->table)->where($where)->inc($feild,$num)->update();
    }


    public function decUserFeild($uid,$feild,$num){
        $where =[];
        $where['uid'] = $uid;
        return Db::name($this->table)->where($where)->dec($feild,$num)->update();
    }

}